/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.market.web.controller;

import java.io.IOException;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonObjectBuilder;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.glassfish.sse.api.ServerSentEventContext;
import org.glassfish.sse.api.ServerSentEventData;
import org.glassfish.sse.api.ServerSentEventHandlerContext;

/**
 *
 * @author Mai
 */
@WebServlet("/changeQuantity")
public class InventoryController extends HttpServlet {
   
    @Inject @ServerSentEventContext("/invUpdate")
    ServerSentEventHandlerContext<InventoryConnection> connections;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pId = req.getParameter("productId");
        int tempQty = Integer.parseInt(req.getParameter("tempQty"));
        int newItemQty = Integer.parseInt(req.getParameter("newItemQty"));
        
         //System.out.println("id" + pId + " pQty" + pQty + " store "+ qtyInStore);
        
         ServerSentEventData data = new ServerSentEventData();
         JsonObjectBuilder b = Json.createObjectBuilder();
         b.add("jId", pId)
                 .add("jtempQty",tempQty)
                 .add("jnewItemQty",newItemQty);
         data.data(b.build().toString());
         data.event("current");
         for(InventoryConnection c: connections.getHandlers())
             c.send(data);
         
         resp.setContentType("text/plain");
         resp.setStatus((HttpServletResponse.SC_OK));
         
               
        
        
    }
    
    
    
}
